//
//  SASelectAddressView.m
//  saasRetail
//
//  Created by 黄志刚 on 2021/8/23.
//

#import "SASelectAddressView.h"
#import "SASelectAddressCell.h"
#import "SAPayRegisterAreaAPI.h"
#import "SAPayRegisterAreaModel.h"

@interface SASelectAddressView ()<UITableViewDelegate, UITableViewDataSource, HTTPAPIDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) SAPayRegisterAreaAPI *payRegisterAreaAPI;
@property (nonatomic, strong) SAPayRegisterAreaAPI *payRegisterAreaAPI2;
@property (nonatomic, strong) SAPayRegisterAreaAPI *payRegisterAreaAPI3;
@property (nonatomic, strong) NSMutableArray<SAPayRegisterAreaModel *> *dataMarr;
@property (nonatomic, strong) NSMutableArray<SAPayRegisterAreaModel *> *dataMarr2;
@property (nonatomic, strong) NSMutableArray<SAPayRegisterAreaModel *> *dataMarr3;
@property (nonatomic, strong) UIButton *cityBtn;
@property (nonatomic, strong) UIButton *regionBtn;
@property (nonatomic, strong) UIButton *addressBtn;
@property (nonatomic, strong) UIView *line;
@property (nonatomic, assign) NSInteger index;
@property (nonatomic, strong) SAPayRegisterAreaModel *selectModel;//省
@property (nonatomic, strong) SAPayRegisterAreaModel *selectModel2;//市
@property (nonatomic, strong) SAPayRegisterAreaModel *selectModel3;//区
@property (nonatomic, strong) NSMutableArray<SAPayRegisterAreaModel *> *areaMarr;

@property (nonatomic, assign) BOOL isFrist;//首次获取数据

@end

@implementation SASelectAddressView

-(instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        [self initUI];
    }
    return self;
}

#pragma mark - HTTPAPIDelegate
- (void)fetchData:(id)data fromServerSuccessedWithAPI:(HTTPAPI *)api {
    if (self.payRegisterAreaAPI == api) {
        self.index = 0;
        self.dataMarr = [SAPayRegisterAreaModel mj_objectArrayWithKeyValuesArray:data[@"data"]];
        [self.tableView reloadData];
        if (self.dataMarr.count > 0) {
            [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:NO];
        }
    }else if (self.payRegisterAreaAPI2 == api) {
        self.index = 1;
        self.dataMarr2 = [SAPayRegisterAreaModel mj_objectArrayWithKeyValuesArray:data[@"data"]];
        [self.tableView reloadData];
        if (self.dataMarr2.count > 0) {
            [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:NO];
        }
    }else if (self.payRegisterAreaAPI3 == api) {
        self.index = 2;
        self.dataMarr3 = [SAPayRegisterAreaModel mj_objectArrayWithKeyValuesArray:data[@"data"]];
        [self.tableView reloadData];
        if (self.dataMarr3.count > 0) {
            [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:NO];
        }
    }
}

- (void)fetchDataFromServerFailedWithError:(NSError *)error API:(HTTPAPI *)api {
    
}

#pragma mark - UITableView Delegate & DataSource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (self.index == 0) {
        return self.dataMarr.count;
    }else if (self.index == 1) {
        return self.dataMarr2.count;
    }
    return self.dataMarr3.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    SASelectAddressCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SASelectAddressCell" forIndexPath:indexPath];
    if (self.index == 0) {
        SAPayRegisterAreaModel *model = self.dataMarr[indexPath.row];
        [cell refreshData:model.areaName AndSelectArea:self.cityBtn.titleLabel.text];
    }else if (self.index == 1) {
        SAPayRegisterAreaModel *model = self.dataMarr2[indexPath.row];
        [cell refreshData:model.areaName AndSelectArea:self.regionBtn.titleLabel.text];
    }else if (self.index == 2) {
        SAPayRegisterAreaModel *model = self.dataMarr3[indexPath.row];
        [cell refreshData:model.areaName AndSelectArea:self.addressBtn.titleLabel.text];
    }
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.index == 0) {
        SAPayRegisterAreaModel *model = self.dataMarr[indexPath.row];
        self.selectModel = model;
        self.payRegisterAreaAPI2.parentAreaCode = model.areaCode;
        [self.payRegisterAreaAPI2 sendRequestToServerWithActivityViewAndMask:GET];
        
        [self.cityBtn setTitle:model.areaName forState:UIControlStateNormal];
        [self.cityBtn setTitleColor:kBlackColor forState:UIControlStateNormal];
        self.regionBtn.hidden = NO;
        [self.regionBtn setTitle:@"请选择" forState:UIControlStateNormal];
        [self.regionBtn setTitleColor:kPinkColor forState:UIControlStateNormal];
        self.addressBtn.hidden = YES;
        
        [self.line mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(self.regionBtn);
            make.top.mas_offset(kScaleNum(87));
            make.height.mas_equalTo(kScaleNum(1));
        }];
    }else if (self.index == 1) {
        SAPayRegisterAreaModel *model = self.dataMarr2[indexPath.row];
        self.selectModel2 = model;
        self.payRegisterAreaAPI3.parentAreaCode = model.areaCode;
        [self.payRegisterAreaAPI3 sendRequestToServerWithActivityViewAndMask:GET];
        
        [self.regionBtn setTitle:model.areaName forState:UIControlStateNormal];
        [self.cityBtn setTitleColor:kBlackColor forState:UIControlStateNormal];
        [self.regionBtn setTitleColor:kBlackColor forState:UIControlStateNormal];
        self.regionBtn.hidden = NO;
        self.addressBtn.hidden = NO;
        [self.addressBtn setTitle:@"请选择" forState:UIControlStateNormal];
        [self.addressBtn setTitleColor:kPinkColor forState:UIControlStateNormal];
        
        [self.line mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(self.addressBtn);
            make.top.mas_offset(kScaleNum(87));
            make.height.mas_equalTo(kScaleNum(1));
        }];
    }else if (self.index == 2) {
        SAPayRegisterAreaModel *model = self.dataMarr3[indexPath.row];
        self.selectModel3 = model;
        [self.addressBtn setTitle:model.areaName forState:UIControlStateNormal];
        [self.tableView reloadData];
        NSMutableArray<SAPayRegisterAreaModel *> *areaMarr = [NSMutableArray array];
        [areaMarr addObject:self.selectModel];
        [areaMarr addObject:self.selectModel2];
        [areaMarr addObject:self.selectModel3];
        self.areaMarr = areaMarr;
        NSMutableArray *marr = [NSMutableArray array];
        [marr addObject:self.dataMarr];
        [marr addObject:self.dataMarr2];
        [marr addObject:self.dataMarr3];
        !self.successBlock ?: self.successBlock(areaMarr, marr);
        self.hidden = YES;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return kScaleNum(35);
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return [[UIView alloc] initWithFrame:CGRectZero];
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [[UIView alloc] initWithFrame:CGRectZero];
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return kScaleNum(0.01);
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return kScaleNum(0.01);
}

#pragma mark - event
-(void)clickedDeleteBtn {
    self.hidden = YES;
}

-(void)refreshData:(NSMutableArray<SAPayRegisterAreaModel *> *)dataMarr {
    if (dataMarr.count != 3) {
        return;
    }
    self.isFrist = YES;
    self.areaMarr = dataMarr;
    SAPayRegisterAreaModel *model1 = dataMarr[0];
    SAPayRegisterAreaModel *model2 = dataMarr[1];
    SAPayRegisterAreaModel *model3 = dataMarr[2];
    self.selectModel = model1;
    self.selectModel2 = model2;
    self.selectModel3 = model3;
    
    self.regionBtn.hidden = NO;
    self.addressBtn.hidden = NO;
    [self.cityBtn setTitle:model1.areaName forState:UIControlStateNormal];
    [self.cityBtn setTitleColor:kBlackColor forState:UIControlStateNormal];
    [self.regionBtn setTitle:model2.areaName forState:UIControlStateNormal];
    [self.regionBtn setTitleColor:kBlackColor forState:UIControlStateNormal];
    [self.addressBtn setTitle:model3.areaName forState:UIControlStateNormal];
    [self.addressBtn setTitleColor:kPinkColor forState:UIControlStateNormal];
    
    [self.payRegisterAreaAPI sendRequestToServerWithActivityViewAndMask:GET];
    self.payRegisterAreaAPI2.parentAreaCode = model1.areaCode;
    [self.payRegisterAreaAPI2 sendRequestToServerWithActivityViewAndMask:GET];
    self.payRegisterAreaAPI3.parentAreaCode = model2.areaCode;
    [self.payRegisterAreaAPI3 sendRequestToServerWithActivityViewAndMask:GET];
    
    [self.line mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.addressBtn);
        make.top.mas_offset(kScaleNum(87));
        make.height.mas_equalTo(kScaleNum(1));
    }];
}

-(void)refreshData:(NSMutableArray<SAPayRegisterAreaModel *> *)dataMarr AndRegionMarr:(NSMutableArray *)regionMarr {
    if (dataMarr.count == 3 && regionMarr.count == 3) {
        SAPayRegisterAreaModel *model1 = dataMarr[0];
        SAPayRegisterAreaModel *model2 = dataMarr[1];
        SAPayRegisterAreaModel *model3 = dataMarr[2];
        self.selectModel = model1;
        self.selectModel2 = model2;
        self.selectModel3 = model3;
        self.regionBtn.hidden = NO;
        self.addressBtn.hidden = NO;
        [self.cityBtn setTitle:model1.areaName forState:UIControlStateNormal];
        [self.cityBtn setTitleColor:kBlackColor forState:UIControlStateNormal];
        [self.regionBtn setTitle:model2.areaName forState:UIControlStateNormal];
        [self.regionBtn setTitleColor:kBlackColor forState:UIControlStateNormal];
        [self.addressBtn setTitle:model3.areaName forState:UIControlStateNormal];
        [self.addressBtn setTitleColor:kPinkColor forState:UIControlStateNormal];
        [self.line mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(self.addressBtn);
            make.top.mas_offset(kScaleNum(87));
            make.height.mas_equalTo(kScaleNum(1));
        }];
        self.dataMarr = regionMarr[0];
        self.dataMarr2 = regionMarr[1];
        self.dataMarr3 = regionMarr[2];
        self.index = 2;
        [self.tableView reloadData];
    }else {
        if (self.dataMarr3.count > 0) {
            self.index = 2;
            [self.tableView reloadData];
        }else {
            [self.tableView reloadData];
        }
    }
    
    if (self.isFrist == YES) {
        self.isFrist = NO;
        NSMutableArray *marr = [NSMutableArray array];
        [marr addObject:self.dataMarr];
        [marr addObject:self.dataMarr2];
        [marr addObject:self.dataMarr3];
        !self.successBlock ?: self.successBlock(self.areaMarr, marr);
    }
}

-(void)clickedCityBtn {
    self.index = 0;
    [self.cityBtn setTitleColor:kPinkColor forState:UIControlStateNormal];
    [self.regionBtn setTitleColor:kBlackColor forState:UIControlStateNormal];
    [self.addressBtn setTitleColor:kBlackColor forState:UIControlStateNormal];
    [self.line mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.cityBtn);
        make.top.mas_offset(kScaleNum(87));
        make.height.mas_equalTo(kScaleNum(1));
    }];
    [self.tableView reloadData];
    if (self.dataMarr.count > 0) {
        [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:NO];
    }
}

-(void)clickedRegionBtn {
    self.index = 1;
    [self.cityBtn setTitleColor:kBlackColor forState:UIControlStateNormal];
    [self.regionBtn setTitleColor:kPinkColor forState:UIControlStateNormal];
    [self.addressBtn setTitleColor:kBlackColor forState:UIControlStateNormal];
    [self.line mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.regionBtn);
        make.top.mas_offset(kScaleNum(87));
        make.height.mas_equalTo(kScaleNum(1));
    }];
    [self.tableView reloadData];
    if (self.dataMarr2.count > 0) {
        [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:NO];
    }
}

-(void)clickedAddressBtn {
    self.index = 2;
    [self.cityBtn setTitleColor:kBlackColor forState:UIControlStateNormal];
    [self.regionBtn setTitleColor:kBlackColor forState:UIControlStateNormal];
    [self.addressBtn setTitleColor:kPinkColor forState:UIControlStateNormal];
    [self.line mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.addressBtn);
        make.top.mas_offset(kScaleNum(87));
        make.height.mas_equalTo(kScaleNum(1));
    }];
    [self.tableView reloadData];
    if (self.dataMarr3.count > 0) {
        [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:NO];
    }
}

#pragma mark - initUI
-(void)initUI {
    self.backgroundColor = kColor(0, 0, 0, 0.3);
    self.index = 0;
    
    UIView *whiteView = [[UIView alloc] initWithFrame:CGRectMake(0, kScreenHeight - kScaleNum(501), kScreenWidth, kScaleNum(501))];
    [self addSubview:whiteView];
    
    UIButton *deleteBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    deleteBtn.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight - kScaleNum(501));
    [deleteBtn addTarget:self action:@selector(clickedDeleteBtn) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:deleteBtn];
    
    UIImageView *bgImageV = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScaleNum(501))];
    bgImageV.image = [UIImage imageNamed:@"pay_bgImageV"];
    [whiteView addSubview:bgImageV];
    
    UILabel *titleLab = [[UILabel alloc] initWithFrame:SARectMake(125, 14, 125, 15)];
    titleLab.text = @"所在地区";
    titleLab.textColor = kBlackColor;
    titleLab.font = kFont(14);
    titleLab.textAlignment = NSTextAlignmentCenter;
    [whiteView addSubview:titleLab];
    
    UIButton *closeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    closeBtn.frame = CGRectMake(kScreenWidth - kScaleNum(60), 0, kScaleNum(60), kScaleNum(44));
    [closeBtn addTarget:self action:@selector(clickedDeleteBtn) forControlEvents:UIControlEventTouchUpInside];
    [closeBtn setImage:[UIImage imageNamed:@"pay_close"] forState:UIControlStateNormal];
    [whiteView addSubview:closeBtn];
    
    UIButton *selectCity = [UIButton buttonWithType:UIButtonTypeCustom];
    [selectCity setTitle:@"请选择" forState:UIControlStateNormal];
    [selectCity setTitleColor:kPinkColor forState:UIControlStateNormal];
    selectCity.titleLabel.font = kFont(14);
    selectCity.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    [selectCity addTarget:self action:@selector(clickedCityBtn) forControlEvents:UIControlEventTouchUpInside];
    [whiteView addSubview:selectCity];
    self.cityBtn = selectCity;
    [selectCity mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(kScaleNum(26));
        make.top.mas_equalTo(kScaleNum(47));
        make.height.mas_equalTo(kScaleNum(40));
    }];
    
    UIButton *regionBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [regionBtn setTitle:@"请选择" forState:UIControlStateNormal];
    [regionBtn setTitleColor:kPinkColor forState:UIControlStateNormal];
    regionBtn.titleLabel.font = kFont(14);
    regionBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    [regionBtn addTarget:self action:@selector(clickedRegionBtn) forControlEvents:UIControlEventTouchUpInside];
    [whiteView addSubview:regionBtn];
    self.regionBtn = regionBtn;
    self.regionBtn.hidden = YES;
    [regionBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(selectCity.mas_right).offset(kScaleNum(15));
        make.top.mas_equalTo(kScaleNum(47));
        make.height.mas_equalTo(kScaleNum(40));
    }];
    
    UIButton *addressBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [addressBtn setTitle:@"请选择" forState:UIControlStateNormal];
    [addressBtn setTitleColor:kPinkColor forState:UIControlStateNormal];
    addressBtn.titleLabel.font = kFont(14);
    addressBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    [addressBtn addTarget:self action:@selector(clickedAddressBtn) forControlEvents:UIControlEventTouchUpInside];
    [whiteView addSubview:addressBtn];
    self.addressBtn = addressBtn;
    self.addressBtn.hidden = YES;
    [addressBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(regionBtn.mas_right).offset(kScaleNum(15));
        make.top.mas_equalTo(kScaleNum(47));
        make.height.mas_equalTo(kScaleNum(40));
    }];
    
    UIView *line = [[UIView alloc] init];
    line.backgroundColor = kPinkColor;
    [whiteView addSubview:line];
    self.line = line;
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.cityBtn);
        make.top.mas_offset(kScaleNum(87));
        make.height.mas_equalTo(kScaleNum(1));
    }];
    
    [whiteView addSubview:self.tableView];
    
    [self.payRegisterAreaAPI sendRequestToServerWithActivityViewAndMask:GET];
}

-(UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, kScaleNum(88), kScreenWidth, kScaleNum(413)) style:UITableViewStyleGrouped];
        _tableView.backgroundColor = [UIColor whiteColor];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.showsHorizontalScrollIndicator = NO;
        _tableView.estimatedRowHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
        _tableView.estimatedSectionFooterHeight = 0;
        [_tableView registerClass:[SASelectAddressCell class] forCellReuseIdentifier:@"SASelectAddressCell"];
    }
    return _tableView;
}

-(SAPayRegisterAreaAPI *)payRegisterAreaAPI {
    if (!_payRegisterAreaAPI) {
        _payRegisterAreaAPI = [SAPayRegisterAreaAPI apiWithDelegate:self];
    }
    return _payRegisterAreaAPI;
}

-(SAPayRegisterAreaAPI *)payRegisterAreaAPI2 {
    if (!_payRegisterAreaAPI2) {
        _payRegisterAreaAPI2 = [SAPayRegisterAreaAPI apiWithDelegate:self];
    }
    return _payRegisterAreaAPI2;
}

-(SAPayRegisterAreaAPI *)payRegisterAreaAPI3 {
    if (!_payRegisterAreaAPI3) {
        _payRegisterAreaAPI3 = [SAPayRegisterAreaAPI apiWithDelegate:self];
    }
    return _payRegisterAreaAPI3;
}

-(NSMutableArray<SAPayRegisterAreaModel *> *)dataMarr {
    if (!_dataMarr) {
        _dataMarr = [NSMutableArray array];
    }
    return _dataMarr;
}

-(NSMutableArray<SAPayRegisterAreaModel *> *)dataMarr2 {
    if (!_dataMarr2) {
        _dataMarr2 = [NSMutableArray array];
    }
    return _dataMarr2;
}

-(NSMutableArray<SAPayRegisterAreaModel *> *)dataMarr3 {
    if (!_dataMarr3) {
        _dataMarr3 = [NSMutableArray array];
    }
    return _dataMarr3;
}

@end
